// $Id$
package lime.xquery.command;

import lime.common.DQLQuery;
import lime.service.SpringApplicationContext;
import lime.service.XQueryService;
import lime.xquery.editor.XQueryEditor;
import lime.xquery.view.XQueryParametersView;
import lime.xquery.view.XQueryResult;
import lime.xquery.view.XQueryResultsView;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.handlers.RadioState;

public class XQueryExecuteHandler extends AbstractHandler {

	private XQueryService service;

	public XQueryExecuteHandler() {
		super();
		service = (XQueryService) SpringApplicationContext.getBean("xqueryService");
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getService(ICommandService.class);
		Command outputCommand = commandService.getCommand("lime.command.xquery.output");
		String output = (String) outputCommand.getState(RadioState.STATE_ID).getValue();
		XQueryResult resultType = XQueryResult.valueOf(output.toUpperCase());
		
		IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
		XQueryResultsView resultsView = (XQueryResultsView) page.findView(XQueryResultsView.ID);
		XQueryParametersView parametersView = (XQueryParametersView) page.findView(XQueryParametersView.ID);
		XQueryEditor editor = (XQueryEditor) page.getActiveEditor();

				
		try {
			
			String unresolvedXQuery = editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();
			String xquery = DQLQuery.resolveParameters(unresolvedXQuery, parametersView.getParameters());
			
			byte[] bytes = service.execute(xquery);
			String text = new String(bytes, "utf-8");
			
			resultsView.update(text, resultType);
			
		} catch (Exception e) {
			resultsView.update(e.getMessage(), XQueryResult.ERROR);
		}

		return null;
	}

}
